package com.text.mqtt_text.mqtt;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.json.JSONObject;

public class ConfigScraper {

    private static final String BASE_URL = "https://xiaozhi.me";
    private static final String AUTH_TOKEN = "Bearer eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjIyODUzOCwidXNlcm5hbWUiOiIrODYxMzI3MzA1NzI1MyIsInRlbGVwaG9uZSI6Iis4NjEzMioqKio3MjUzIiwicm9sZSI6InVzZXIiLCJpYXQiOjE3NTUxNDA0MDYsImV4cCI6MTc2MjkxNjQwNn0.ao7KRGOWk0A9wj4qQhvJyyUBhaPjPi9YdBwE1jwH-tq3E0gf6Pz9KbgDrQqeAjImMbNg8LvhYp7cM67K8_KMDw"; // 替换为实际的Token

    public static void config() {
        // 设置输出目录为当前目录下的 downloaded_configs 文件夹
        String outputDir = "downloaded_configs";

        // 指定 agent ID
        String agentId = "170573"; // 您指定的agent ID

        // 创建爬虫实例并获取配置内容
        ConfigScraper scraper = new ConfigScraper();
        boolean success = scraper.getConfigContent(agentId, outputDir);

        if (success) {
            System.out.println("配置内容已成功保存！");
        } else {
            System.out.println("获取配置内容失败！");
        }
    }

    /**
     * 获取指定 agent 的配置内容
     *
     * @param agentId   agent 的 ID
     * @param outputDir 保存配置文件的目录
     * @return 是否成功获取配置内容
     */
    public boolean getConfigContent(String agentId, String outputDir) {
        try {
            // 创建输出目录（如果不存在）
            Path outputPath = Paths.get(outputDir);
            if (!Files.exists(outputPath)) {
                Files.createDirectories(outputPath);
            }

            // 构建请求 URL
            String url = BASE_URL + "/api/agents/" + agentId;
            System.out.println("正在获取 agent " + agentId + " 的配置内容...");
            System.out.println("请求 URL: " + url);

            // 发送 GET 请求
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Authorization", AUTH_TOKEN);

            int responseCode = connection.getResponseCode();
            System.out.println("响应状态码: " + responseCode);

            if (responseCode == 200) {
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 解析 JSON 响应
                JSONObject jsonResponse = new JSONObject(response.toString());
                if (!jsonResponse.getBoolean("success")) {
                    System.out.println("API 返回错误: " + jsonResponse.getString("message"));
                    return false;
                }

                // 获取 memory 字段内容
                JSONObject data = jsonResponse.getJSONObject("data").getJSONObject("agent");
                String memoryContent = data.optString("memory", "");
                if (memoryContent.isEmpty()) {
                    System.out.println("未找到 memory 内容");
                    return false;
                }

                // 保存到文件
                String fileName = "memory.txt";
                Path filePath = Paths.get(outputDir, fileName);
                Files.write(filePath, memoryContent.getBytes("UTF-8"));

                System.out.println("memory 内容已保存到: " + filePath);
                System.out.println("内容长度: " + memoryContent.length() + " 字符");

                return true;
            } else {
                System.out.println("请求失败，状态码: " + responseCode);
                return false;
            }
        } catch (Exception e) {
            System.out.println("处理过程中出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
}